//
//  DeviceHelper.m
//  uteped_sdk
//
//  Created by mateng on 2024/2/29.
//

#import "DeviceHelper.h"
#import "Const.h"
#import "StringUtils.h"
#import "LogUtils.h"
#import "SPHelper.h"
#import "UTEPedDB.h"

#define TAG @"DeviceHelper"

@interface DeviceHelper ()

@property(nonatomic, strong) NSString* address;
@property(nonatomic, strong) NSTimer *keepConnectTimer;
@property(nonatomic, strong) NSUserDefaults *addressUserDefaults;

@property(nonatomic, assign) BOOL isRemoving;
- (void)removeData:(NSString*)address;

@end

@implementation DeviceHelper

static DeviceHelper* instance = nil;

+ (DeviceHelper*) shareInstance
{
    if ( instance == nil ) {
        instance = [[DeviceHelper alloc] init];
    }
    return instance;
}

- (id)init {
    if (self = [super init]) {
        self.blueMgr = [UTEBluetoothMgr sharedInstance];
        self.deviceMgr = [UTEDeviceMgr sharedInstance];
        
        NSString *address = [[NSUserDefaults standardUserDefaults] objectForKey:KEY_ADDRESS];
        if (address != nil && address.length > 0) {
            [self onDeviceConnected:address];
        }
    }
    
    return self;
}

- (void)onDeviceConnected:(nonnull NSString *)address {
    NSString* addressMd5 = [StringUtils md5String:address];
    if (self.addressUserDefaults == nil) {
        self.addressUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:addressMd5];
        [[NSUserDefaults standardUserDefaults] addSuiteNamed:addressMd5];
    }
    
    [self startCheckTimer];
}

- (void)onDeviceDisconnect:(NSString *)address {
    [self removeUnbindDeviceData:address];
    self.address = nil;
}

- (void)putObject:(NSString*) key value:(nullable id) value {
    [self.addressUserDefaults setObject:value forKey:key];
}

- (id)getObject:(NSString*) key {
    return [self.addressUserDefaults objectForKey:key];
}

- (void)startCheckTimer {
    [LogUtils log:TAG message:@"startCheckTimer"];
    [self canelCheckTimer];
    self.keepConnectTimer = [NSTimer scheduledTimerWithTimeInterval:40.0 target:self selector:@selector(autoConnectDevice) userInfo:nil repeats:YES];
}

- (void)canelCheckTimer {
    [LogUtils log:TAG message:@"canelCheckTimer"];
    if (self.keepConnectTimer != nil) {
        [self.keepConnectTimer invalidate];
    }
    self.keepConnectTimer = nil;
}

- (void)autoConnectDevice {
    [LogUtils log:TAG message:@"autoConnectDevice"];
    NSString *address = [[NSUserDefaults standardUserDefaults] objectForKey:KEY_ADDRESS];
    
    if (![self.blueMgr isOpenBluetooth]) {
        [LogUtils log:TAG message:@"bluetooth is not enabled"];
        return;
    }
    
    if ([self.blueMgr.connnectModel isConnected]) {
        [LogUtils log:TAG message:@"device already connected"];
        return;
    }
    
    if (address == nil || address.length <= 0) {
        [LogUtils log:TAG message:@"address is empty"];
        return;
    }
    
    UTEModelDevice *device = self.blueMgr.connnectModel;
    if (device == nil || device.identifier == nil) {
        NSString* identifier = [[SPHelper shareInstance] getObject:address defaultValue:nil];
        if (identifier != nil){
            device = [[UTEModelDevice alloc] init];
            device.identifier = identifier;
        }
    }
    
    [self.blueMgr connectDevice:device];
}

- (void)removeUnbindDeviceData:(NSString *)address {
    if (address == nil) {
        return;
    }
    
    NSString* addressMd5 = [StringUtils md5String:address];
    [[NSUserDefaults standardUserDefaults] removeSuiteNamed:addressMd5];
    [[SPHelper shareInstance] removeObject:KEY_PAIRED];
    [[SPHelper shareInstance] removeObject:KEY_PAIRID];
    
    if (self.isRemoving) {
        return;
    }
    
    self.isRemoving = YES;
    [self performSelector:@selector(removeData:) withObject:address];
}

- (void)removeData:(NSString*) address {
    [[UTEPedDB shareInstance] removeData:address];
    self.isRemoving = NO;
}

@end
